package com.zkthink.ceres.order.util;

import com.zkthink.ceres.common.event.OrderCancelEvent;
import com.zkthink.ceres.common.event.OrderFinishEvent;
import com.zkthink.ceres.common.event.OrderPaidEvent;
import com.zkthink.ceres.order.dao.OrderProductMapper;
import com.zkthink.ceres.order.dto.AdminOrderDTO;
import com.zkthink.ceres.order.dto.event.OrderEventDTO;
import com.zkthink.ceres.order.entity.Order;
import com.zkthink.database.mybatis.conditions.Wraps;
import com.zkthink.dozer.DozerUtils;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import com.zkthink.ceres.order.dao.OrderMapper;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单发布事件的工具
 */
@Component
@AllArgsConstructor
public class OrderEventUtil {

    private OrderMapper orderMapper;

    private OrderProductMapper orderProductMapper;

    private DozerUtils dozerUtils;

    private ApplicationEventPublisher publisher;

    /**
     * 发布订单支付事件
     * @param payOrder
     */
    public void publishOrderPaidEvent(Order payOrder){
        OrderPaidEvent<OrderEventDTO> paidEvent = dozerUtils.map(payOrder, OrderPaidEvent.class);
        //如果是主订单，要把子订单也查出来
        if(payOrder.getParentId() == 0){
            List<Order> childOrderList = orderMapper.selectList(Wraps.<Order>lbQ().eq(Order::getParentId,payOrder.getId()));
            List<OrderEventDTO> adminOrderDTOList = new ArrayList<>();
            for(Order order:childOrderList){
                OrderEventDTO orderEventDTO = new OrderEventDTO();
                dozerUtils.map(order,orderEventDTO);
                orderEventDTO.setOrderId(order.getId());
                Integer productCount = orderProductMapper.queryProductCount(order.getOrderCode());
                orderEventDTO.setProductCount(productCount);
                adminOrderDTOList.add(orderEventDTO);
            }
            paidEvent.setChildOrderDTOList(adminOrderDTOList);
        } else {
            Integer productCount = orderProductMapper.queryProductCount(payOrder.getOrderCode());
            paidEvent.setProductCount(productCount);
        }
        //发布订单支付事件
        publisher.publishEvent(paidEvent);
    }

    /**
     * 发布订单完成事件
     * @param order
     */
    public void publishOrderFinishEvent(Order order) {
        OrderFinishEvent orderFinishEvent = dozerUtils.map(order, OrderFinishEvent.class);
        publisher.publishEvent(orderFinishEvent);
    }

    /**
     * 发布订单取消事件
     * @param order
     */
    public void publishOrderCancelEvent(Order order) {
        OrderCancelEvent orderCancelEvent = dozerUtils.map(order, OrderCancelEvent.class);
        publisher.publishEvent(orderCancelEvent);
    }
}
